$(function () {
    $.widget('ui.aywSlider', {
		options: {
			interval: 1000 * 5,
			selector: 'li',
			auto: true,
			tiper: '.tip_arrow',
			offset: 0,
			rotateHimage: false, 
			load: ''//load new url,this will load content & switcher
		},
		_handler: null,
		_index: 0,
		
		_create: function() {
			var self = this;
			self._handler = $(this.options.selector, this.element);
			
			if (self.options.auto) {
				setInterval(function() {
					self._swap();
				}, self.options.interval);
				// end auto
			}
			
			// manual click
			self._handler.click(function(){
				self._switchContext(self._switchContext(this));
				self._index = $(this).index();
				return false;
			});
			
			// rotate image handler
			if (self.options.rotateHimage) {
				self._rotateImage();
			}
		},
		
		_rotateImage : function() {
			var self = this;
			self._handler.each(function() {
				if (self.options.rotateHimage[$(this).index()]) {
					_current = self.options.rotateHimage[$(this).index()];
				} else {
					_current = [0, '#ff8b19', '#ff8b19'];
				}
				
				var img = $('img', this), 
					src = img.attr('src'),
                    left = $(this).offset().left,
                    top = $(this).offset().top,
                	cx = $(this).position().left - $(this).width/2 + 20,
                	cy = $(this).position().top - $(this).height/2 + 20,
                    angle = 0;
                $(this).html('');
                var R = Raphael(this, 145, 145);
             	var imgContainer = R.rect(11,11, 86, 86, 0).rotate(_current[0], cx, cy).attr({'stroke': _current[2], "stroke-width": 3, 'fill': '#fff'});
             	var img = R.image(src, 14, 14, 80, 80);
                img.rotate(_current[0], cx, cy).hover(function(){
	                	imgContainer.attr({"stroke": _current[2], "stroke-width": 3});
	                }, function() {
	                	imgContainer.attr({"stroke": _current[1], "stroke-width": 3});
	                }
            	);							
			});
 			
		},
		
		_swap : function(){
			var self = this;
			if (self._index < self._handler.length-1) {
				self._index++;
			} else {
				self._index = 0;
				if (self.options.load) {
					$.get(self.options.load, function(data){
						// data = [{handler:"", context:""},{}]
						// todo
					})
				}
			}
			self._switchContext(self._handler[self._index]);
		},
		
		_switchContext: function(e) {
			var self = this;
			if (!e) e = this._handler.index[this._index];
			var id = $(e).attr('data-config');
			if (!id) return false;
			// must a field name context
			var _str = $.parseJSON(id), _id = _str.context, 
				_obj = $('#' + _id), _class = _obj.attr('class');
			_obj.siblings('.' + _class).stop(true,true).hide();
			_obj.find(self.options.tiper).css({
				left: $(e).position().left+$(e).width()/2 + self.options.offset
			});
			self._handler.find('a:first').removeClass('on');
			$('a:first', e).addClass('on');
			_obj.fadeIn(1000);			
			
		}
		
	});
});

